﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace hello_accinv_New_
{
    public partial class AddProductForm : Form
    {
        Database db;
        public string loginUser;

        public AddProductForm()
        {
            InitializeComponent();
            db = new Database();
        }

        private void btnAddProduct_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (MessageBox.Show("Confirm?", "Add Product Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {                    
                    // Get category id
                    DataTable dt = db.Select("CategoryID, Unit, CodeName", "Category", "Name = '" + cmbCategory.SelectedItem.ToString() + "'");
                    string categoryID = dt.Rows[0]["CategoryID"].ToString();
                    string unit = dt.Rows[0]["Unit"].ToString();
                    string categoryCodeName = dt.Rows[0]["CodeName"].ToString();

                    // Get latest product code
                    dt = db.Select("PCode", "Product", "PCode LIKE '" + categoryCodeName + "%' ORDER BY PCode DESC LIMIT 1");
                    string newPCode = categoryCodeName + "001";
                    if (dt.Rows.Count != 0)
                    {
                        newPCode = categoryCodeName + FillZero((Int32.Parse(dt.Rows[0]["PCode"].ToString().Substring(3,3)) + 1).ToString());
                    }

                    // Image => Bytes
                    byte[] image = null;
                    if (txtboxImagePath.Text.Length > 0)
                    {
                        FileInfo imageInfo = new FileInfo(txtboxImagePath.Tag.ToString());
                        image = new byte[imageInfo.Length];
                        FileStream imagestream = imageInfo.OpenRead();
                        imagestream.Position = 0;
                        imagestream.Read(image, 0, image.Length);
                        imagestream.Close();
                    }

                    // Do insert
                    // Product
                    db.Insert("Product",
                               "'" + newPCode + "','" + txtboxName.Text + "','" + categoryID + "','" + txtboxPrice.Text + "','" + txtboxQty.Text + "','" + txtboxDetail.Text + "','" + image + "','1'");
                    // ActionLog
                    db.Insert("ActionLog", "'" + CustomDateTime.GetCurrentDate() + "','" + CustomDateTime.GetCurrentTime() + "','" + loginUser + " added new product " + txtboxName.Text + ".'");

                    if (Int32.Parse(txtboxQty.Text) > 0)
                    {
                        db.Insert("Purchase", "0,'" + newPCode + "','" + CustomDateTime.GetCurrentDate() + "','" + CustomDateTime.GetCurrentTime() + "','" + txtboxQty.Text + "','" + txtboxRemark.TabIndex + "'");
                    }

                    MessageBox.Show("New Product\n------------------------------\nCode\t" + newPCode + "\nName\t" + txtboxName.Text + "\nCategory\t" + cmbCategory.SelectedItem.ToString() + "\nPrice\t" + txtboxPrice.Text + " Baht\nStock qty.\t" + txtboxPrice.Text + " " + unit + "\n------------------------------");
                    Dispose();
                }
            }
            else
            {
                MessageBox.Show("Recheck product data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        private bool IsValidate()
        {
            bool validate = true;

            if (cmbCategory.SelectedIndex == -1 || cmbCategory.SelectedItem.ToString().Contains("-"))
                validate = false;
            if (txtboxName.Text.Equals(""))
                validate = false;
            if (txtboxPrice.Text.Equals(""))
                validate = false;

            return validate;
        }

        private void cmbCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCategory.SelectedIndex != -1)
            {
                DataTable dt = db.Select("CategoryID, Unit", "Category", "Name = '" + cmbCategory.SelectedItem.ToString() + "'");
                lbUnit.Text = dt.Rows[0]["Unit"].ToString();
                grpboxAddProductDetail.Text = cmbCategory.SelectedItem.ToString() + " Details";
            }
            else
            {
                cmbCategory.SelectedIndex = -1;
                lbUnit.Text = "Unit";
                grpboxAddProductDetail.Text = "Product Details";
            }
        }

        private string FillZero(string input)
        {
            string output = "";
            int addCount = (3 - input.Length);

            for (int i = 0; i < addCount; i++)
            {
                output += "0";
            }
            output += input;

            return output;
        }

        private void LoadCategoryList()
        {
            DataTable dt = db.Select("Name", "Category", "1 ORDER BY Name ASC");
            List<string> lst = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                lst.Add(dt.Rows[i]["Name"].ToString());
            }
            cmbCategory.DataSource = lst;
            cmbCategory.SelectedIndex = -1;
        }

        private void AddProduct_Load(object sender, EventArgs e)
        {
            LoadCategoryList();
        }

        private void btnBrowseImage_Click(object sender, EventArgs e)
        {
            if (imageDialog.ShowDialog() == DialogResult.OK)
            {
                string ext = imageDialog.FileName.Substring(imageDialog.FileName.Length - 3);
                if (ext.Equals("bmp", StringComparison.OrdinalIgnoreCase) ||
                    ext.Equals("jpg", StringComparison.OrdinalIgnoreCase) ||
                    ext.Equals("png", StringComparison.OrdinalIgnoreCase))
                {
                    txtboxImagePath.Text = new FileInfo(imageDialog.FileName).Name;
                    txtboxImagePath.Tag = imageDialog.FileName;
                    pictureBox1.Image = new Bitmap(imageDialog.FileName);
                }
                else
                {
                    MessageBox.Show("Not image file");
                    txtboxImagePath.Text = "";
                    pictureBox1.Image = null;
                }
            }
        }

        private void btnClearImage_Click(object sender, EventArgs e)
        {
            txtboxImagePath.Text = "";
            pictureBox1.Image = null;
        }

        private void txtboxPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !(Char.IsDigit(e.KeyChar) || (Keys)e.KeyChar == Keys.Back || e.KeyChar == '.');
        }

        private void txtboxQty_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !(Char.IsDigit(e.KeyChar) || (Keys)e.KeyChar == Keys.Back);
        }
    }
}
